package com.threefire.quickstart;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * @author zhouyanxiang
 * @Date 2021-01-2021/1/10-0:01
 */
public class Client {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                .option(ChannelOption.SO_RCVBUF,1024 * 32)
                .option(ChannelOption.SO_SNDBUF,1024 * 32)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) {
                        channel.pipeline().addLast(new ClientHandler());
                    }
                });
        // 4. 服务器端绑定端口并启动服务
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8765).syncUninterruptibly();
        // 5. 发送一条数据到服务端
        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty".getBytes()));
        // 6. 休眠1s
        Thread.sleep(1000);
        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty! again !!!".getBytes()));
        // 7. 同步阻塞关闭监听并释放资源
        channelFuture.channel().closeFuture().sync();
        workGroup.shutdownGracefully();
    }

}
